/*
 * Copyright 2011-2012 by The Regents of the University of California Licensed
 * under the Apache License, Version 2.0 (the "License"); you may not use this
 * file except in compliance with the License. you may obtain a copy of the
 * License from
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package edu.ucsd.db.bassarisk.query.expression.visitor;

import java.util.ArrayList;
import java.util.List;

import edu.ucsd.db.bassarisk.exception.VisitorException;
import edu.ucsd.db.bassarisk.query.ValidationTraversalLog;
import edu.ucsd.db.bassarisk.query.expression.Expressions.BooleanNot;
import edu.ucsd.db.bassarisk.query.expression.Expressions.Expression;
import edu.ucsd.db.bassarisk.query.expression.Expressions.KeywordMatchExpr;
import edu.ucsd.db.bassarisk.query.expression.Expressions.NonterminalExpr;
import edu.ucsd.db.bassarisk.query.expression.Expressions.PositionPredExpr;

/**
 * This visitor seeks invalid use of positional predicates.
 * 
 * Specifically, this validator seeks instances of the NOT boolean expression in
 * the subtree under position predicates. Since positional bindings within a NOT
 * sub-expression are required to not match any position in the document for a
 * satisfying set of bindings, it is not possible to reason about relative
 * positions between existing positions and non-existant positions.
 */
public class PositionPredicateSaftyValidationTraversal extends
    SupertypeDeferingExpressionTreeVisitor<Void, ValidationTraversalLog> {
  /**
   * Collects all BooleanNot expressions in expression tree.
   */
  private class NegationFinder extends ExpressionTreeCollectionTraversal<BooleanNot> {
    @Override
    public Void visitBooleanNot(final BooleanNot expr, final List<BooleanNot> arg)
        throws VisitorException {
      arg.add(expr);
      expr.getSubExpr().accept(this, arg);
      return null;
    }
  }

  /**
   * Finds all BooleanNot expressions in the forest of sub-expressions and, for
   * each BooleanNot expression found, adds an error message to the
   * ValidationTraversalArgs.
   */
  private void findNegations(final NonterminalExpr expr,
                             final ValidationTraversalLog arg)
      throws VisitorException {
    NegationFinder finder = new NegationFinder();
    List<BooleanNot> nots = new ArrayList<BooleanNot>();
    for (Expression subExpr : expr.getSubExprs()) {
      subExpr.accept(finder, nots);
    }
    for (BooleanNot not : nots) {
      String msg =
          "Position expression safty violated by %s sub-expression at column %s. "
              + "Please make sure %s expressions are not nested within position "
              + "predicate expressions.";
      arg.addError(expr,
                   String.format(msg, not.friendlyName(), not.getStartColumn(),
                                 not.friendlyName()));
    }
  }

  @Override
  public Void visitKeywordMatchExpr(final KeywordMatchExpr expr,
                                    final ValidationTraversalLog arg)
      throws VisitorException {
    return null;
  }

  @Override
  public Void visitNonterminalExpr(final NonterminalExpr expr,
                                   final ValidationTraversalLog arg)
      throws VisitorException {
    for (Expression subExpr : expr.getSubExprs()) {
      subExpr.accept(this, arg);
    }
    return null;
  }

  @Override
  public Void visitPositionPredExpr(final PositionPredExpr expr,
                                    final ValidationTraversalLog arg)
      throws VisitorException {
    this.findNegations(expr, arg);
    return this.visitNonterminalExpr(expr, arg);
  }
}
